﻿using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using OpenQA.Selenium;
using Ro.AssistFunction.BackNodeInfo;
using Ro.AssistFunction.OutputManage;
using Ro.Common.RoInterface.RoWebAction;
using Ro.Common.RoInterface.UserType;
using Ro.DriverEvent.FindElement;

namespace Ro.DriverEvent.WebAction
{
    /// <summary>
    /// 上传操作
    /// </summary>
    public class WebUpdate : IWebUpdateFunc
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="sigNode">文件上传UpdateSelect</param>
        /// <returns>返回是否完成</returns>
        /// <remarks>Only Windows</remarks>
        public WebActionResult UpdateSelect(XmlNode sigNode)
        {
            //返回值
            WebActionResult back;
            ExtractNeedInfo extractNeedInfo = new ExtractNeedInfo();
            //提取超时
            TimeSpan timeout = extractNeedInfo.ExtractTimeout(sigNode);

            //提取元素
            string value = extractNeedInfo.ExtractAttributeValue(sigNode, "web:RoWebElementID");

            //获取webelement
            FindWebElement findWebElement = new FindWebElement(value, timeout);
            IWebElement webElement = findWebElement.WebElement;
            try
            {
                //获取桌面路径
                if (webElement == null)
                {
                    back = BackActionResult.BackWebResult(false, value, "Update操作遭遇查找元素失败，获取元素为null"); //结果
                }
                else
                {
                    webElement.Click();
                    //下拉值
                    string filepath = extractNeedInfo.ExtractInnerText(sigNode, "web:FileValue");
                    //转换为正常的输入值
                    ArgsIntoValue argsIntoValue = new ArgsIntoValue(filepath);
                    filepath = argsIntoValue.BackValue;

                    if (!File.Exists(filepath))
                    {
                        back = BackActionResult.BackWebResult(false, value, "Update操作遭遇失败，带上传的文件不存在"); //结果
                    }
                    else
                    {
                        Thread.Sleep(1000);
                        //发送文件路径
                        SendKeys.SendWait(@"^a");
                        Thread.Sleep(500);
                        SendKeys.SendWait(@"{BACKSPACE}");
                        Thread.Sleep(500);
                        SendKeys.SendWait(filepath);
                        Thread.Sleep(500);
                        SendKeys.SendWait(@"%o");
                        Thread.Sleep(500);

                        back = BackActionResult.BackWebResult(true, value, "没有附加信息"); //结果
                    }
                }
            }
            catch (Exception e)
            {
                back = BackActionResult.BackWebResult(true, value, "WebUpdate操作遭遇System异常"); //结果
                ExceptionOutPut.SystemExceptionOut("WebUpdate", e);
            }
            return back;
        }
    }
}